﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ModelDto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common
{
    /// <summary>
    /// 微信小程序 辅助类
    /// </summary>
    public  class WXAppletHelper: IWXAppletHelper
    {
        private readonly IOptions<WXConfig> WXConfig;
        private ILogger<WXAppletHelper> _logger;

        private readonly IRedisHelper _redisHelper;

        private string _AppId="";
        private string _AppSecret="";

        public WXAppletHelper(IOptions<WXConfig> options, ILogger<WXAppletHelper> logger, IRedisHelper redisHelper)
        {
            WXConfig = options;
            _logger = logger;

            _AppId = WXConfig.Value.WXApplet.AppId;
            _AppSecret = WXConfig.Value.WXApplet.AppSecret;

            _redisHelper = redisHelper;
        }


        /// <summary>
        /// 微信小程序 授权登录 GET
        /// 请求地址： https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        /// 参数：
        /// appid string        小程序 appId
        /// secret string       小程序 appSecret
        /// js_code string      登录时获取的 code
        /// grant_type string   授权类型，此处只需填写 authorization_code
        /// </summary>
        public WXAppletLoginResponse WXAppletLogin(string code)
        {
            _logger.LogDebug($"微信小程序授权开始：code={code}");
            WXAppletLoginResponse response = null;

            try
            {
                if (string.IsNullOrWhiteSpace(code))
                {
                    _logger.LogDebug("code 为空");
                    return response;
                }

                string appId = _AppId;
                string appSecret = _AppSecret;

                if (string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(appSecret))
                {
                    _logger.LogDebug("appId || appSecret 为空");
                    return response;
                }
                _logger.LogDebug($"微信小程序 appId = {appId}，appSecret = {appSecret}");

                string requestUrl = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";

                JsonResultL httpResponse = WebHttpRequestHelper.HttpGet(requestUrl);

                if (httpResponse.Success)
                {
                    response = new WXAppletLoginResponse();
                    //httpResponse.Data
                    response = JsonConvert.DeserializeObject<WXAppletLoginResponse>(httpResponse.Data.ToString());
                }
                return response;
            }
            catch (Exception e)
            {
                _logger.LogDebug($"微信小程序授权系统出错：{e.Message}");
                return response;
            }
           

            
        }

        /// <summary>
        /// 微信小程序 获取Token GET 
        /// 请求地址：https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        /// 参数：
        /// grant_type string 填写 client_credential
        /// appid string 小程序唯一凭证，即 AppID，可在「微信公众平台 - 设置 - 开发设置」页中获得。（需要已经成为开发者，且帐号没有异常状态）
        /// secret string 小程序唯一凭证密钥，即 AppSecret，获取方式同 appid
        /// </summary>
        /// <returns></returns>
        //public WXAppletAccessTokenResponse GetAccessToken()
        public string GetAccessToken()
        {
            WXAppletAccessTokenResponse response = null;

            try
            {
                string tokenRedis = _redisHelper.GetValue($"token_{_AppId}");
                if (!string.IsNullOrWhiteSpace(tokenRedis))
                {
                    return tokenRedis;
                }
                if (string.IsNullOrWhiteSpace(_AppId) || string.IsNullOrWhiteSpace(_AppSecret))
                {
                    _logger.LogDebug("appId || appSecret 为空");
                    return "";
                }
              

                string requestUrl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={_AppId}&secret={_AppSecret}";

                JsonResultL httpResponse = WebHttpRequestHelper.HttpGet(requestUrl);

                if (httpResponse.Success)
                {
                    response = new WXAppletAccessTokenResponse();
                    //httpResponse.Data
                    response = JsonConvert.DeserializeObject<WXAppletAccessTokenResponse>(httpResponse.Data.ToString());


                    if (response !=null)
                    {
                        _redisHelper.SetValue($"token_{_AppId}", response.access_token, new TimeSpan(0, 0, response.expires_in));

                        return response.access_token;
                    }
                }
                return "";
            }
            catch (Exception e)
            {
                _logger.LogDebug($"微信小程序授权系统出错：{e.Message}");
                return "";
            }

        }

        /// <summary>
        /// 获取用户手机号
        /// https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
        /// post access_token code
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public WXAppletGetPhoneNumberResponse WXAppletGetTel(string code)
        {

            string token = GetAccessToken();
            _logger.LogDebug($"微信小程序获取手机号");
            WXAppletGetPhoneNumberResponse response = null;

            try
            {

                if (string.IsNullOrWhiteSpace(_AppId) || string.IsNullOrWhiteSpace(_AppSecret))
                {
                    _logger.LogDebug("appId || appSecret 为空");
                    return response;
                }

                string requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";

                object obj = new {
                    access_token= token,
                    code=code
                };

                JsonResultL httpResponse = WebHttpRequestHelper.HttpPost(requestUrl,JsonConvert.SerializeObject(obj));

                if (httpResponse.Success)
                {
                    response = new WXAppletGetPhoneNumberResponse();
               
                    response = JsonConvert.DeserializeObject<WXAppletGetPhoneNumberResponse>(httpResponse.Data.ToString());
                }
            }
            catch (Exception e)
            {
                _logger.LogDebug($"微信小程序授权系统出错：{e.Message}");
            }

            return response;
        }

        /// <summary>
        /// 获取token 备用
        /// </summary>
        /// <returns></returns>
        public string GetAccessTokenFresh()
        {
            WXAppletAccessTokenResponse response = null;

            try
            {
                if (string.IsNullOrWhiteSpace(_AppId) || string.IsNullOrWhiteSpace(_AppSecret))
                {
                    _logger.LogDebug("appId || appSecret 为空");
                    return "";
                }
               

                string requestUrl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={_AppId}&secret={_AppSecret}";

                JsonResultL httpResponse = WebHttpRequestHelper.HttpGet(requestUrl);

                if (httpResponse.Success)
                {
                    response = new WXAppletAccessTokenResponse();
       
                    response = JsonConvert.DeserializeObject<WXAppletAccessTokenResponse>(httpResponse.Data.ToString());


                    if (response != null)
                    {
                        return response.access_token;
                    }
                }
                return "";
            }
            catch (Exception e)
            {
                _logger.LogDebug($"微信小程序授权系统出错：{e.Message}");
                return "";
            }
        }
    }
}
